package com.ml.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {
	private Socket socket;
	private InputStream inputStream;
	private PrintStream printStream;
	public final static String WEB_ROOT = "c:\\webapps\\";

	public Processor(Socket socket) {
		this.socket = socket;
		try {
			inputStream = this.socket.getInputStream();
			printStream = new PrintStream(this.socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		String fileName = parse(inputStream);
		sendFile(fileName);
	}

	public String parse(InputStream in) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String fileName = null;
		try {
			String httpMsg = reader.readLine();
			String[] content = httpMsg.split(" ");
			if (content.length != 3) {
				sendErrorMsg(400, "请求错误！");
				return null;
			}
			fileName = content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}

	public void sendFile(String fileName) {
		File file = new File(Processor.WEB_ROOT + fileName);
		if (!file.exists()) {
			sendErrorMsg(404, "请求的资源不存在！");
			return;
		}
		try {
			inputStream = new FileInputStream(file);
			byte[] content = new byte[(int) file.length()];
			inputStream.read(content);

			printStream.println("HTTP/1.0 200 Query");
			printStream.println("content-length:" + content.length);
			printStream.println();
			printStream.write(content);
			printStream.flush();
			printStream.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendErrorMsg(int errorCode, String errorMsg) {
		printStream.println("HTTP/1.0 " + errorCode + " " + errorMsg);
		printStream.println("content-type: text/html");
		printStream.println();
		printStream.println("<html>");
		printStream.println("<head>");
		printStream.println("<title>错误信息!</title>");
		printStream.println("</head>");
		printStream.println("<body>");
		printStream.println("<h1>ErrorCode:" + errorCode + ",ErrorMsg:" + errorMsg + "</h1>");
		printStream.println("</body>");
		printStream.println("</html>");
		printStream.flush();
		printStream.close();
		try {
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
